package com.business.dashboard.controller;

import com.business.dashboard.entity.BusinessPlan;
import com.business.dashboard.service.BusinessPlanService;
import com.business.dashboard.utils.JwtUtil;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户端业务计划控制器
 *
 * @author Claude
 * @since 2025-07-09
 */
@Slf4j
@RestController
@RequestMapping("/api/business-plans")
@Validated
public class BusinessPlanController {

    @Autowired
    private BusinessPlanService businessPlanService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 创建业务计划
     */
    @PostMapping("")
    public ResultUtil<BusinessPlan> createBusinessPlan(HttpServletRequest request,
                                                       @RequestBody Map<String, Object> planData) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));

            BusinessPlan businessPlan = new BusinessPlan();
            businessPlan.setUserId(userId);
            businessPlan.setTitle((String) planData.get("title"));
            businessPlan.setCompanyName((String) planData.get("companyName"));
            businessPlan.setIndustry((String) planData.get("industry"));
            businessPlan.setBusinessModel((String) planData.get("businessModel"));
            businessPlan.setTargetMarket((String) planData.get("targetMarket"));
            businessPlan.setProblemStatement((String) planData.get("problemStatement"));
            businessPlan.setSolution((String) planData.get("solution"));
            businessPlan.setPlanData(planData.toString());
            businessPlan.setStatus("draft");

            BusinessPlan createdPlan = businessPlanService.createPlan(businessPlan);
            return ResultUtil.success("创建业务计划成功", createdPlan);
        } catch (Exception e) {
            return ResultUtil.error("创建业务计划失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的业务计划列表
     */
    @GetMapping("")
    public ResultUtil<List<BusinessPlan>> getUserBusinessPlans(HttpServletRequest request,
                                                              @RequestParam(defaultValue = "1") Integer page,
                                                              @RequestParam(defaultValue = "10") Integer size) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));

            List<BusinessPlan> plans = businessPlanService.getUserPlans(userId, page, size);
            return ResultUtil.success("获取业务计划列表成功", plans);
        } catch (Exception e) {
            log.error("获取业务计划列表失败", e);
            return ResultUtil.error("获取业务计划列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取业务计划详情
     */
    @GetMapping("/{id}")
    public ResultUtil<BusinessPlan> getBusinessPlanById(HttpServletRequest request,
                                                        @PathVariable @NotNull Long id) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));

            BusinessPlan plan = businessPlanService.getPlanById(id);
            if (plan == null) {
                return ResultUtil.error(404, "业务计划不存在");
            }

            // 检查权限：只能查看自己的业务计划
            if (!plan.getUserId().equals(userId)) {
                return ResultUtil.error(403, "无权访问该业务计划");
            }

            return ResultUtil.success("获取业务计划详情成功", plan);
        } catch (Exception e) {
            log.error("获取业务计划详情失败，id: {}", id, e);
            return ResultUtil.error("获取业务计划详情失败：" + e.getMessage());
        }
    }

    /**
     * 更新业务计划
     */
    @PutMapping("/{id}")
    public ResultUtil<BusinessPlan> updateBusinessPlan(HttpServletRequest request,
                                                       @PathVariable @NotNull Long id,
                                                       @RequestBody Map<String, Object> planData) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));

            BusinessPlan existingPlan = businessPlanService.getPlanById(id);
            if (existingPlan == null) {
                return ResultUtil.error(404, "业务计划不存在");
            }

            // 检查权限：只能更新自己的业务计划
            if (!existingPlan.getUserId().equals(userId)) {
                return ResultUtil.error(403, "无权修改该业务计划");
            }

            // 更新字段
            existingPlan.setTitle((String) planData.get("title"));
            existingPlan.setCompanyName((String) planData.get("companyName"));
            existingPlan.setIndustry((String) planData.get("industry"));
            existingPlan.setBusinessModel((String) planData.get("businessModel"));
            existingPlan.setTargetMarket((String) planData.get("targetMarket"));
            existingPlan.setProblemStatement((String) planData.get("problemStatement"));
            existingPlan.setSolution((String) planData.get("solution"));
            existingPlan.setPlanData(planData.toString());

            BusinessPlan updatedPlan = businessPlanService.updatePlan(existingPlan);
            return ResultUtil.success("更新业务计划成功", updatedPlan);
        } catch (Exception e) {
            log.error("更新业务计划失败，id: {}", id, e);
            return ResultUtil.error("更新业务计划失败：" + e.getMessage());
        }
    }

    /**
     * 删除业务计划
     */
    @DeleteMapping("/{id}")
    public ResultUtil<String> deleteBusinessPlan(HttpServletRequest request,
                                                 @PathVariable @NotNull Long id) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));

            BusinessPlan existingPlan = businessPlanService.getPlanById(id);
            if (existingPlan == null) {
                return ResultUtil.error(404, "业务计划不存在");
            }

            // 检查权限：只能删除自己的业务计划
            if (!existingPlan.getUserId().equals(userId)) {
                return ResultUtil.error(403, "无权删除该业务计划");
            }

            boolean success = businessPlanService.deletePlan(id);
            if (success) {
                return ResultUtil.success("删除业务计划成功");
            } else {
                return ResultUtil.error("删除业务计划失败");
            }
        } catch (Exception e) {
            log.error("删除业务计划失败，id: {}", id, e);
            return ResultUtil.error("删除业务计划失败：" + e.getMessage());
        }
    }

    /**
     * 获取业务计划模板
     */
    @GetMapping("/templates")
    public ResultUtil<List<Map<String, Object>>> getBusinessPlanTemplates() {
        try {
            // 返回预设的模板数据
            List<Map<String, Object>> templates = new ArrayList<>();

            Map<String, Object> techTemplate = new HashMap<>();
            techTemplate.put("id", "tech_startup");
            techTemplate.put("name", "科技创业模板");
            techTemplate.put("description", "适用于科技类创业项目的商业计划书模板");
            techTemplate.put("industry", "科技");
            templates.add(techTemplate);

            Map<String, Object> retailTemplate = new HashMap<>();
            retailTemplate.put("id", "retail_business");
            retailTemplate.put("name", "零售业务模板");
            retailTemplate.put("description", "适用于零售行业的商业计划书模板");
            retailTemplate.put("industry", "零售");
            templates.add(retailTemplate);

            Map<String, Object> serviceTemplate = new HashMap<>();
            serviceTemplate.put("id", "service_business");
            serviceTemplate.put("name", "服务业务模板");
            serviceTemplate.put("description", "适用于服务行业的商业计划书模板");
            serviceTemplate.put("industry", "服务");
            templates.add(serviceTemplate);

            return ResultUtil.success("获取模板成功", templates);
        } catch (Exception e) {
            log.error("获取业务计划模板失败", e);
            return ResultUtil.error("获取模板失败：" + e.getMessage());
        }
    }

    /**
     * 分享业务计划
     */
    @PostMapping("/{id}/share")
    public ResultUtil<Map<String, Object>> shareBusinessPlan(HttpServletRequest request,
                                                             @PathVariable @NotNull Long id) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));

            BusinessPlan plan = businessPlanService.getPlanById(id);
            if (plan == null) {
                return ResultUtil.error(404, "业务计划不存在");
            }

            // 检查权限
            if (!plan.getUserId().equals(userId)) {
                return ResultUtil.error(403, "无权分享该业务计划");
            }

            // 生成分享码（简单实现）
            String shareCode = "bp_" + id + "_" + System.currentTimeMillis();

            Map<String, Object> shareInfo = new HashMap<>();
            shareInfo.put("shareCode", shareCode);
            shareInfo.put("shareUrl", "/shared/business-plan/" + shareCode);
            shareInfo.put("expiresAt", System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000L); // 7天后过期

            return ResultUtil.success("分享成功", shareInfo);
        } catch (Exception e) {
            log.error("分享业务计划失败，id: {}", id, e);
            return ResultUtil.error("分享失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            return authorization.substring(7);
        }
        return null;
    }
}